<template>
  <div class="citySearch">
    <div class="row align-items-center text-light bg-info head-wrap">
      <div class="col">
        <input
          type="text"
          class="search-input w-100 rounded text-center px-2"
          placeholder="输入城市名或拼音"
          required
          v-model.trim="strInput"
        >
      </div>
    </div>
    <div class="search-cont" v-show="strInput" ref="search">
      <ul>
        <li
          v-for="item in list"
          :key="item.id"
          class="py-1 border-bottom"
          @click="changeCity(item.name)"
        >{{item.name}}</li>
        <li v-if="disBool">没有找到匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  name: "CitySearch",
  props: {
    allCity: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      strInput: "",
      list: [],
      timer: null
    };
  },
  watch: {
    strInput() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      // if (!this.strInput) {
      //   this.list = [];
      //   return;
      // }
      this.timer = setTimeout(() => {
        let res = [];
        for (let i in this.allCity) {
          this.allCity[i].forEach(val => {
            if (
              val.name.indexOf(this.strInput) > -1 ||
              val.spell.indexOf(this.strInput) > -1
            ) {
              // console.log(val);
              res.push(val);
            }
          });
        }
        this.list = res;
      }, 100);
    }
  },
  computed: {
    disBool() {
      return !this.list.length;
    }
  },
  components: {},
  methods: {
    changeCity(city) {
      // console.log(city);
      this.$store.dispatch("change", city);
      // this.strInput = "";
      // this.list = [];
      // this.timer = null;
      this.$router.push("/");
    }
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.search, {
      click: true,
      mouseWheel: true
    });
  }
};
</script>


<style scoped>
.search-cont {
  position: absolute;
  top: 4.9rem;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(255, 255, 255, 1);
  z-index: 1;
  overflow: hidden;
}
</style>
